﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace DataSystem
{
    public class DataService
    {
        public Dictionary<string, IDataProvider> Providers { get; set; }

        public DirectoryInfo WorkingDir;

        public DataService()
        {
            Providers = new Dictionary<string, IDataProvider>();

            LoadAllProviders();
        }

        public DataService(string dir)
        {
            Providers = new Dictionary<string, IDataProvider>();

            WorkingDir = new DirectoryInfo(dir);
            LoadAllProviders();
        }

        public void LoadAllProviders()
        {


            if (WorkingDir == null)
            {
                var workingDir = Directory.GetCurrentDirectory();
                WorkingDir = new DirectoryInfo(workingDir);
            }
            foreach (var file in WorkingDir.GetFiles("*Provider.dll"))
            {

                Assembly assm = Assembly.LoadFrom(file.FullName);
                Type[] types = assm.GetTypes();
                foreach (var type in types)
                {
                    try
                    {
                        IDataProvider provider = (IDataProvider)Activator.CreateInstance(type);
                        Providers.Add(type.Name, provider);
                    }
                    catch
                    {
                    }
                }             


            }

        }

    }
}
